package com.lagou.controller;

import com.lagou.entity.FileSystem;
import org.csource.common.NameValuePair;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@RestController
public class FileUploader {

    public static final String HTTP_FASTDFS_STORAGE_HOST = "http://fastdfs-storage.vhost/";

    @PostMapping("avatarUpload")
    public FileSystem upload(@RequestParam("portrait") MultipartFile portrait, HttpServletRequest request) {
        FileSystem fileSystem = null;

        //获取上传的文件对象
//        MultipartFile file = request.getFile("portrait");

        if (portrait != null) {
            try {
                fileSystem = uploadToFastDFS(portrait);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("file uploaded: " + fileSystem);

        return fileSystem;
    }

    public FileSystem uploadToFastDFS(MultipartFile file) throws Exception {
        // 从文件对象中获取文件的原始名称
        String originalFilename = file.getOriginalFilename();
        // 通过字符串截取的方式，从文件原始名中获取文件的后缀
        String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        // 为了避免文件因为同名而覆盖，生成全新的文件名
        String newFilename = UUID.randomUUID().toString() + "." + ext;
        // 创建web服务器保存文件的目录(预先创建好/Users/gilbert/upload目录，否则系统找不到路径，会抛异常)
        File toSaveFile = new File("/Users/gilbert/upload/" + newFilename);
        // 保存文件
        file.transferTo(toSaveFile);
        // 获取服务器对绝对路径
        String newFilePath = toSaveFile.getAbsolutePath();

        // 把文件从服务器上传到FastDFS
        ClientGlobal.initByProperties("config/fastdfs-client.properties");
        TrackerClient trackerClient = new TrackerClient();
        TrackerServer trackerServer = trackerClient.getConnection();
        StorageClient1 storageClient = new StorageClient1(trackerServer, null);
        NameValuePair[] list = new NameValuePair[1];
        list[0] = new NameValuePair("filename", originalFilename);
        String fileId = storageClient.upload_file1(newFilePath, ext, list);
        trackerServer.close();

        // 封装FileSystem对象
        return new FileSystem(fileId, HTTP_FASTDFS_STORAGE_HOST + fileId, originalFilename);
    }
}
